package com.example.administrator.managesystem.fragment.firstpage;

import android.app.SharedElementCallback;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.administrator.managesystem.R;
import com.example.administrator.managesystem.activity.firstpage.circle.interfaces.OnItemCollectClickListener;
import com.example.administrator.managesystem.activity.firstpage.circle.interfaces.OnItemRepostClickListener;
import com.example.administrator.managesystem.activity.firstpage.circle.ui.SendCircleActivity;
import com.example.administrator.managesystem.activity.firstpage.circle.adapter.HomeIndexAdapter;
import com.example.administrator.managesystem.activity.firstpage.circle.constans.P;
import com.example.administrator.managesystem.activity.firstpage.circle.interfaces.OnItemPictureClickListener;
import com.example.administrator.managesystem.activity.firstpage.circle.ui.ImagePreviewActivity;
import com.example.administrator.managesystem.activity.firstpage.circle.utils.Utils;
import com.example.administrator.managesystem.base.BaseFragment;
import com.example.administrator.managesystem.base.BaseHelper;
import com.example.administrator.managesystem.bean.MyShareCircleBean;
import com.example.administrator.managesystem.presenter.firstpage.FirstPagePresenter;
import com.example.administrator.managesystem.ui.FirstPageView;
import com.example.administrator.managesystem.utils.ShareUtil;
import com.example.administrator.managesystem.view.RepostDialog;
import com.example.administrator.managesystem.view.StateLayout;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * Created by Jue on 2018/6/2.
 */

public class CircleFragment extends BaseFragment implements FirstPageView {
    private XRecyclerView recyclerView;
    private HomeIndexAdapter homeIndexAdapter;
    private Bundle mReenterState;
    private int itemPosition;
    private LinearLayout send_ll;
    private int loadPage=1;
    private FirstPagePresenter firstPagePresenter;
    private List<MyShareCircleBean.DataBean> superList= new ArrayList<>();
    private String share_url;

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
            recyclerView =  view.findViewById(R.id.recyclerView);
            send_ll=view.findViewById(R.id.send_ll);


    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tudou_circle;
    }



    @Override
    protected void doBusiness() {
        firstPagePresenter=new FirstPagePresenter(this);
        homeIndexAdapter = new HomeIndexAdapter(getActivity(),superList);
        BaseHelper.setLinearLayoutManagerVertical(getActivity(),recyclerView,homeIndexAdapter);
        Log.e("msg"," firstPagePresenter.myShareCircle:"+ firstPagePresenter);
        firstPagePresenter.myShareCircle(ShareUtil.getUserId(getActivity()),ShareUtil.getUserToken(getActivity()),1,5,0,getActivity());
        send_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(SendCircleActivity.class,false);
            }
        });

        //0代表刷新，1代表加载更多
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

                loadPage=1;
                firstPagePresenter.myShareCircle(ShareUtil.getUserId(getActivity()),ShareUtil.getUserToken(getActivity()),1,5,0,getActivity());
                recyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                loadPage++;
                firstPagePresenter.myShareCircle(ShareUtil.getUserId(getActivity()),ShareUtil.getUserToken(getActivity()),loadPage,5,1,getActivity());
                Log.e("msg","loadPage:"+loadPage);
                recyclerView.loadMoreComplete();
            }

        });
        homeIndexAdapter.addPictureListener(new OnItemPictureClickListener() {
            @Override
            public void onItemPictureClick(int item, int position, String url, List<String> urlList, ImageView imageView) {
                itemPosition = item;
                Intent intent = new Intent(getActivity(), ImagePreviewActivity.class);
                intent.putStringArrayListExtra("imageList", (ArrayList<String>) urlList);
                intent.putExtra(P.START_ITEM_POSITION, itemPosition);
                intent.putExtra(P.START_IAMGE_POSITION, position);
//                 ActivityOptions compat = ActivityOptions.makeSceneTransitionAnimation( ,imageView, imageView.getTransitionName());
                startActivity(intent);
            }
        });

        homeIndexAdapter.addCollectListener( new OnItemCollectClickListener() {
            @Override
            public void onItemCollectClick(int position, View view,String breeding_id,ImageView imageView) {
                //ToastUtils.showToast(getActivity(),"点了"+position,Toast.LENGTH_SHORT);
                firstPagePresenter.collectRequest(ShareUtil.getUserId(getActivity()),breeding_id,ShareUtil.getUserToken(getActivity()),position,getActivity());

            }
        });

        homeIndexAdapter.addRepostListener(new OnItemRepostClickListener() {
            @Override
            public void onItemRepostClick(int position, View view, final String breeding_id, final String url) {
                Log.e("msg","url:"+url);
                share_url=url;
                final RepostDialog repostDialog=new RepostDialog(getActivity());
                repostDialog.setOnCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        repostDialog.dismiss();
                    }
                });
                repostDialog.setOnFriendCircleListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        firstPagePresenter.repostRequest(ShareUtil.getUserId(getActivity()),breeding_id,ShareUtil.getUserToken(getActivity()),0,getActivity());
                        repostDialog.dismiss();
                    }
                });
                repostDialog.setOnQQListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        firstPagePresenter.repostRequest(ShareUtil.getUserId(getActivity()),breeding_id,ShareUtil.getUserToken(getActivity()),1,getActivity());
                        repostDialog.dismiss();
                    }
                });
                repostDialog.setOnQQZoneListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        firstPagePresenter.repostRequest(ShareUtil.getUserId(getActivity()),breeding_id,ShareUtil.getUserToken(getActivity()),2,getActivity());
                        repostDialog.dismiss();
                    }
                });

                repostDialog.setOnWechatListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        firstPagePresenter.repostRequest(ShareUtil.getUserId(getActivity()),breeding_id,ShareUtil.getUserToken(getActivity()),3,getActivity());
                        repostDialog.dismiss();
                    }
                });
                repostDialog.show();
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE){
                    send_ll.setVisibility(View.VISIBLE);
                }else{
                    send_ll.setVisibility(View.GONE);
                }

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

    }

    @Override
    public void updateUI(final List<MyShareCircleBean.DataBean> list, int type) {
        if(list.isEmpty()){
            return;
        }
        Log.e("msg","superList:"+superList);
        if(type==1){
            superList.addAll(list);
        }else{
            superList.clear();
            superList.addAll(list);
        }
       // stateLayout.showContentView();
       homeIndexAdapter.notifyItemRangeChanged(0,superList.size()-1);
    }

    @Override
    public void repost(String url,int type) {
        UMImage thumb = new UMImage(getActivity(),R.drawable.app_icon);
        UMWeb web = new UMWeb(share_url);
        web.setTitle("昭觉县农产品质量追溯");//标题
        web.setThumb(thumb);  //缩略图
        switch(type){
            case 0:
                //;
                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).withMedia(web)
                        .setCallback(shareListener).share();
                break;
            case 1:
                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.QQ).withMedia(web)
                        .setCallback(shareListener).share();
                break;
            case 2:
                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.QZONE).withMedia(web)
                        .setCallback(shareListener).share();
                break;
            case 3:

                new ShareAction(getActivity()).setPlatform(SHARE_MEDIA.WEIXIN).withMedia(web)
                        .setCallback(shareListener).share();
                break;


        }


    }

    @Override
    public void showSuccess(int position) {
      //  imageView.setImageResource(R.drawable.collect_seleted);
        superList.get(position).setIs_collection(true);
        homeIndexAdapter.notifyItemRangeChanged(0,superList.size()-1);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mReenterState = new Bundle(data.getExtras());
        int startingPosition = mReenterState.getInt(P.CURRENT_ITEM_POSITION);
        if (startingPosition != itemPosition) {//如果不是同一个item就滚动到指定的item
            recyclerView.scrollToPosition(itemPosition);
        }
        postponeEnterTransition();
        recyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                recyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
                recyclerView.requestLayout();
                startPostponedEnterTransition();
                return true;
            }
        });
    }

    private final SharedElementCallback mCallback = new SharedElementCallback() {

        @Override
        public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
            if (mReenterState != null) {
                //从别的界面返回当前界面
                int startingPosition = mReenterState.getInt(P.START_IAMGE_POSITION);
                int currentPosition = mReenterState.getInt(P.CURRENT_IAMGE_POSITION);
                if (startingPosition != currentPosition) {//如果不是之前的那张图片就切换到指定的图片
                    String newTransitionName = Utils.getNameByPosition(itemPosition,currentPosition);
                    View newSharedElement = recyclerView.findViewWithTag(newTransitionName);
                    if (newSharedElement != null) {
                        names.clear();
                        names.add(newTransitionName);
                        sharedElements.clear();
                        sharedElements.put(newTransitionName, newSharedElement);
                    }
                }
                mReenterState = null;
            }
        }
    };

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }
        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(getContext(),"分享成功！",Toast.LENGTH_LONG).show();
        }
        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(getActivity(),"分享成功！"+t.getMessage(),Toast.LENGTH_LONG).show();
        }
        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(getActivity(),"分享取消！",Toast.LENGTH_LONG).show();
        }
    };

}
